const { observable, action } = require('mobx-miniprogram');

// 缓存管理器Store
export const cacheManagerStore = observable({
  // 缓存统计数据
  cacheStats: null,
  
  // 缓存分组列表
  cacheGroups: [],
  
  // 操作面板
  showActionSheet: false,
  actionItems: ['清理全部缓存', '清理选定分组', '清理低优先级缓存', '缓存详情'],
  currentAction: null,
  currentGroup: null,
  
  // 页面状态
  isLoad: false,
  isAdmin: false,
  
  // 计算属性：获取总缓存使用百分比
  get totalCacheUsage() {
    if (!this.cacheStats || !this.cacheStats.total) return 0;
    return parseFloat(((this.cacheStats.total.size / this.cacheStats.total.limit) * 100).toFixed(1));
  },
  
  // 计算属性：获取总缓存大小格式化后的字符串
  get totalCacheSize() {
    if (!this.cacheStats || !this.cacheStats.total) return '0 KB';
    return this.cacheStats.total.size.toFixed(2) + ' KB';
  },
  
  // Action: 设置缓存统计数据
  setCacheStats: action(function(stats) {
    this.cacheStats = stats;
  }),
  
  // Action: 设置缓存分组列表
  setCacheGroups: action(function(groups) {
    this.cacheGroups = groups;
  }),
  
  // Action: 设置当前选中的分组
  setCurrentGroup: action(function(group) {
    this.currentGroup = group;
  }),
  
  // Action: 设置操作面板显示状态
  setShowActionSheet: action(function(show) {
    this.showActionSheet = show;
  }),
  
  // Action: 设置当前操作
  setCurrentAction: action(function(action) {
    this.currentAction = action;
  }),
  
  // Action: 设置加载和管理员状态
  setPageState: action(function(isLoad, isAdmin) {
    this.isLoad = isLoad;
    this.isAdmin = isAdmin;
  }),
  
  // Action: 格式化缓存统计数据
  formatCacheStats: action(function(rawStats) {
    if (!rawStats) return null;
    
    return {
      total: {
        count: rawStats.total.count,
        size: rawStats.total.size.toFixed(2),
        limit: rawStats.total.limit,
        usage: ((rawStats.total.size / rawStats.total.limit) * 100).toFixed(1),
        color: this.getUsageColor(rawStats.total.size, rawStats.total.limit)
      }
    };
  }),
  
  // Action: 根据使用率获取颜色
  getUsageColor: action(function(size, limit) {
    if (limit <= 0) return '#999999';
    
    const usage = (size / limit) * 100;
    
    if (usage >= 80) {
      return '#ff0000'; // 危险红色
    } else if (usage >= 60) {
      return '#ff9900'; // 警告橙色
    } else {
      return '#0066cc'; // 正常蓝色
    }
  }),
  
  // Action: 加载缓存统计数据
  loadCacheStats: action(async function() {
    try {
      const cacheHelper = require('../../../../../helpers/cache_helper.js');
      const pageHelper = require('../../../../../helpers/page_helper.js');
      
      const stats = cacheHelper.getStats();
      if (!stats) {
        pageHelper.showModal('获取缓存统计失败', '请稍后重试');
        return false;
      }
      
      // 格式化统计数据用于显示
      const formattedStats = this.formatCacheStats(stats);
      
      // 提取分组数据
      const groups = [];
      for (const groupName in stats.groups) {
        const groupData = stats.groups[groupName];
        groups.push({
          name: groupName,
          count: groupData.count,
          size: groupData.size.toFixed(2),
          color: this.getUsageColor(groupData.size, stats.total.limit)
        });
      }
      
      // 按大小排序
      groups.sort((a, b) => b.size - a.size);
      
      this.setCacheStats(formattedStats);
      this.setCacheGroups(groups);
      
      return true;
    } catch (error) {
      console.error('加载缓存统计失败', error);
      return false;
    }
  }),
  
  // Action: 清理所有缓存
  clearAllCache: action(function() {
    try {
      const cacheHelper = require('../../../../../helpers/cache_helper.js');
      const pageHelper = require('../../../../../helpers/page_helper.js');
      
      const result = cacheHelper.clearAll();
      if (result) {
        pageHelper.showToast('清理缓存成功');
        this.loadCacheStats();
      } else {
        pageHelper.showModal('清理缓存失败', '请稍后重试');
      }
      
      return result;
    } catch (error) {
      console.error('清理缓存失败', error);
      return false;
    }
  }),
  
  // Action: 清理指定分组缓存
  clearGroupCache: action(function(groupName) {
    try {
      const cacheHelper = require('../../../../../helpers/cache_helper.js');
      const pageHelper = require('../../../../../helpers/page_helper.js');
      
      if (!groupName) {
        pageHelper.showModal('参数错误', '分组名称不能为空');
        return false;
      }
      
      const result = cacheHelper.clearGroup(groupName);
      if (result) {
        pageHelper.showToast(`清理 ${groupName} 分组缓存成功`);
        this.loadCacheStats();
      } else {
        pageHelper.showModal('清理缓存失败', '请稍后重试');
      }
      
      return result;
    } catch (error) {
      console.error('清理分组缓存失败', error);
      return false;
    }
  }),
  
  // Action: 清理低优先级缓存
  clearLowPriorityCache: action(function() {
    try {
      const cacheHelper = require('../../../../../helpers/cache_helper.js');
      const pageHelper = require('../../../../../helpers/page_helper.js');
      
      const result = cacheHelper.clearLowPriority();
      if (result) {
        pageHelper.showToast('清理低优先级缓存成功');
        this.loadCacheStats();
      } else {
        pageHelper.showModal('清理缓存失败', '请稍后重试');
      }
      
      return result;
    } catch (error) {
      console.error('清理低优先级缓存失败', error);
      return false;
    }
  }),
  
  // Action: 处理操作面板点击
  handleActionClick: action(function(index) {
    this.setShowActionSheet(false);
    
    switch (index) {
      case 0: // 清理全部缓存
        this.clearAllCache();
        break;
      case 1: // 清理选定分组
        if (this.currentGroup) {
          this.clearGroupCache(this.currentGroup);
        }
        break;
      case 2: // 清理低优先级缓存
        this.clearLowPriorityCache();
        break;
      case 3: // 缓存详情
        this.showCacheDetails();
        break;
    }
  }),
  
  // Action: 显示缓存详情
  showCacheDetails: action(function() {
    // 可以实现跳转到详情页面的逻辑
    wx.navigateTo({
      url: '/projects/oa/pages/admin/tools/cache_details/cache_details'
    });
  })
}); 